package com.jyy.prefabricated.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jyy.prefabricated.dto.BatchDto;
import com.jyy.prefabricated.entity.Course;
import com.jyy.prefabricated.entity.CourseCategory;
import com.jyy.prefabricated.entity.CourseFile;
import com.jyy.prefabricated.entity.CourseWithBLOBs;
import com.jyy.prefabricated.enums.BaseStatusEnum;
import com.jyy.prefabricated.enums.CourseTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.CourseFileMapper;
import com.jyy.prefabricated.mapper.CourseMapper;
import com.jyy.prefabricated.utils.HttpUtil;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import net.polyv.vod.v1.util.VodSignUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @version 1.0.0
 * @author: zjj
 */
@Log4j
@Slf4j
@Service
public class CourseService {

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private CourseFileMapper courseFileMapper;

    @Resource
    private CourseFileMapper fileMapper;
    @Value("${polyv.userId}")
    private String userId;

    @Value("${polyv.secretKey}")
    private String secretKey;

    /**
     * 新增
     *
     * @param course
     * @return
     */
    public int insert(CourseWithBLOBs course) throws Exception {
        course.setStatus(BaseStatusEnum.INVALID.getValue());
//        if (course.getXiaoeUrl() != null) {
//            int i=course.getXiaoeUrl().lastIndexOf("/");
//            int j=course.getXiaoeUrl().lastIndexOf("?");
//            course.setResourceId(course.getXiaoeUrl().substring(i+1,j));
//        }
        courseMapper.insert(course);
        saveCourseId2File(course.getFiles(), course.getId(), course.getType());
        return course.getId();
    }

    /**
     * 将课程id写入课程文件
     *
     * @param files
     * @param id
     */
    public void saveCourseId2File(List<CourseFile> files, Integer id, Integer type) throws Exception {
        if (CourseTypeEnum.RECORDING.getValue().equals(type)) {
            if (files != null && files.size() > 0) {
                for (CourseFile file : files) {
                    file.setCourseId(id);
                    if (file.getPath() != null && !"".equals(file.getPath())) {
                        //公共参数,填写自己的实际参数
                        String ptime = String.valueOf(System.currentTimeMillis());
                        //业务参数
                        String url = String.format("http://api.polyv.net/v2/video/%s/get-video-info", userId);
                        String vid = file.getPath();

                        Map<String, String> requestMap = new HashMap<>();
                        requestMap.put("ptime", ptime);
                        requestMap.put("vid", vid);
                        requestMap.put("sign", VodSignUtil.getSign(requestMap, secretKey));
                        String response = HttpUtil.postFormBody(url, requestMap);

                        JSONObject res = JSONObject.parseObject(response);
                        JSONArray results = res.getJSONArray("data");
                        if (results != null) {
                            JSONObject first = results.getJSONObject(0);
                            JSONObject basicInfo = first.getJSONObject("basicInfo");
                            Long time = basicInfo.getLong("duration");
                            file.setSeconds(time);
                        }

                    }
                }
                fileMapper.updateBatch(files);
            }
        } else {
            if (files != null && files.size() > 0) {
                for (CourseFile file : files) {
                    file.setCourseId(id);
                }
                fileMapper.updateBatch(files);
            }
        }
    }

    /**
     * 更新
     *
     * @param course
     * @return
     */
    public int update(CourseWithBLOBs course) throws Exception {
        if (course.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
//        if (course.getXiaoeUrl() != null) {
//            int i=course.getXiaoeUrl().lastIndexOf("/");
//            int j=course.getXiaoeUrl().lastIndexOf("?");
//            course.setResourceId(course.getXiaoeUrl().substring(i+1,j));
//        }
        saveCourseId2File(course.getFiles(), course.getId(), course.getType());
        return courseMapper.updateByPrimaryKeySelective(course);
    }

    /**
     * 检查当前的课程章节视频时长是否更新
     */
    public void checkCourseSecond() throws Exception {
        List<CourseFile> files = courseFileMapper.selectAll();

        if (files != null && files.size() > 0) {
            for (CourseFile file : files) {
                file.setCourseId(file.getCourseId());
                if (file.getPath() != null && !"".equals(file.getPath())) {
                    //公共参数,填写自己的实际参数
                    String ptime = String.valueOf(System.currentTimeMillis());
                    //业务参数
                    String url = String.format("http://api.polyv.net/v2/video/%s/get-video-info", userId);
                    String vid = file.getPath();

                    Map<String, String> requestMap = new HashMap<>();
                    requestMap.put("ptime", ptime);
                    requestMap.put("vid", vid);
                    requestMap.put("sign", VodSignUtil.getSign(requestMap, secretKey));
                    String response = HttpUtil.postFormBody(url, requestMap);

                    JSONObject res = JSONObject.parseObject(response);
                    JSONArray results = res.getJSONArray("data");
                    if (results != null) {
                        JSONObject first = results.getJSONObject(0);
                        JSONObject basicInfo = first.getJSONObject("basicInfo");
                        Long time = basicInfo.getLong("duration");
                        file.setSeconds(time);
                    }
                }
            }
            fileMapper.updateBatch(files);
        }
    }


    /**
     * 批量修改状态
     *
     * @param dto
     * @return
     */
    public int batchUpdateStatus(BatchDto dto) {
        if (dto.getIds().size() == 0) {
            throw new CustomException("参数id不能为空");
        }
        return courseMapper.batchUpdateStatus(dto.getIds(), dto.getStatus());
    }

    /**
     * 批量删除
     *
     * @param dto
     * @return
     */
    public int batchDelete(BatchDto dto) {
        if (dto.getIds().size() == 0) {
            throw new CustomException("参数id不能为空");
        }
        return courseMapper.batchDelete(dto.getIds());
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Integer id) {
        CourseWithBLOBs course = courseMapper.selectByPrimaryKey(id);
        course.setDeleted(true);
        return courseMapper.updateByPrimaryKeySelective(course);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public CourseWithBLOBs selectById(Integer id) {
        return courseMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据resourceId查询
     *
     * @param resourceId
     * @return
     */
    public Course selectByResourceId(String resourceId) {
        return courseMapper.selectByResourceId(resourceId);
    }

    /**
     * 根据参数查询列表
     *
     * @param courseName 课程名称
     * @param lecturer   导师
     * @param type       课程类型
     * @param categoryId 课程分类id
     * @param status     课程状态
     * @return
     */
    public List<CourseWithBLOBs> selectByParams(Integer type, String courseName, Integer categoryId, String lecturer, Integer status) {
        return courseMapper.selectByParams(type, courseName, categoryId, lecturer, status);
    }

    /**
     * 根据参数查询包含课程子分类的列表
     *
     * @param type        课程类型
     * @param courseName  课程名称
     * @param categoryIds 课程分类id列表
     * @param lecturer    导师
     * @param status      课程状态
     * @param orderStr    排序
     * @return
     */
    public List<CourseWithBLOBs> selectDeepByParams(Integer type, Integer plateId, Boolean recommend, String courseName, List<Integer> categoryIds, String lecturer, Integer status, String orderStr) {
        return courseMapper.selectByParamsDeep(type, plateId, recommend, courseName, categoryIds, lecturer, status, orderStr);
    }

    /**
     * 移动端查询课程列表
     *
     * @param type        课程类型
     * @param courseName  课程名称
     * @param categoryIds 课程分类id列表
     * @param lecturer    导师
     * @param status      课程状态
     * @param top         是否置顶
     * @param orderStr    排序
     * @return
     */
    public List<Course> selectWithPackageByParamsDeep(Integer type, Integer plateId, Boolean recommend, String courseName, List<Integer> categoryIds, String lecturer, Integer status, Boolean top, String orderStr, Integer sortStatus) {
        return courseMapper.selectWithPackageByParamsDeep(type, plateId, recommend, courseName, categoryIds, lecturer, status, top, orderStr, sortStatus);
    }

    /**
     * 根据分类上下级关系查询分类列表
     *
     * @param categoryId
     * @return
     */
    public List<Integer> selectDeepCategoryIds(Integer categoryId) {
        List<Integer> categoryIds = new ArrayList<>();
        if (categoryId != null) {
            List<CourseCategory> list = courseCategoryService.selectAll();
            List<CourseCategory> categories = courseCategoryService.findCategoryIdByPid(categoryId, list);
            categoryIds.addAll(categories.stream().map(e -> e.getId()).collect(Collectors.toList()));
            categoryIds.add(categoryId);
        }
        return categoryIds;
    }


}
